package com.evil.kingdom.listener;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.evil.kingdom.handler.SseHandler;
import com.evil.kingdom.listener.event.MinuteTickEvent;
import com.evil.kingdom.pojo.dto.alive.AliveMessage;
import com.evil.kingdom.pojo.entity.config.Config;
import com.evil.kingdom.pojo.entity.config.value.Almanac;
import com.evil.kingdom.pojo.enums.ConfigEnum;
import com.evil.kingdom.service.config.ConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 分-时钟监听器
 *
 * @author LY
 * @date 2024/5/1810:18
 */
@Slf4j
@Component
@AllArgsConstructor
public class MinuteTickListener implements ApplicationListener<MinuteTickEvent> {

    private final ConfigService configService;
    private final SseHandler sseHandler;

    @Override
    public void onApplicationEvent(MinuteTickEvent event) {
        LocalDateTime time = event.getTime();
        // 处理每分事件
        log.debug("Minute ticked at: {}", LocalDateTimeUtil.formatNormal(time));
        ConfigEnum configEnum = ConfigEnum.ALMANAC;
        Almanac almanac = (Almanac) configService.isExistByEnum(configEnum).orElseGet(Almanac::new);
        almanac.addDay();
        configService.getRepository().save(new Config(configEnum.name(), almanac.toJsonStr()));

        // 发送时间
        sseHandler.sendWorld(new AliveMessage<>(almanac));
    }
}
